<script setup>
import { onMounted, reactive, ref, toRaw } from '@vue/runtime-core';
import Type, { Size } from './type';
import { regionDateShortcuts3 } from '@utils/config';
import { Search, Download } from '@element-plus/icons-vue';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const props = defineProps({
    gutter: {
        type: Number,
        default: 12,
    },
    items: Array,
    onLoad: Boolean, //一般页面一开始加载的时候就有搜索条件，这时候onMounted就把条件传出去，PageWrapper中一开始就不加载了
});
/**
 * filter 筛选按钮点击
 */
const emit = defineEmits(['filter', 'export', 'param', 'onLineNum']);

const datas = ref(
    (() => {
        let oneLine = 24;
        let line = 1;
        let allWidth = 0;

        let array = [[]];
        props.items.forEach(item => {
            //获取元素宽度
            let width = item.width == 0 ? 0 : item.width || Size[item.type];
            //重新赋值给元素
            item.width = width;
            //加起来宽度
            allWidth += width;
            //不满一行添加进array末尾数组
            if (allWidth <= oneLine) {
                array[array.length - 1].push(item);
            } else {
                //满一行line加1, allWidth - oneLine, 下一次相当于重新计算
                line += 1;
                allWidth = width;
                //先新增一个元素
                array.push([]);
                //再添加元素
                array[array.length - 1].push(item);
            }
        });
        emit('onLineNum', line);
        return array;
    })()
);

const queryForm = reactive({
    time: '', // DATE_RANGE || DATE
});

/**
 * 如果传default，就要带个key, 和上图对应
 */
let likes = [];
props.items.forEach((item, index) => {
    if (item.default) {
        queryForm[item.key] = item.default;
    }
    if (item.likes) {
        likes.push(item.key);
        queryForm.likes = likes.join(',');
    }
});

const clear = () => {
    if (JSON.stringify(route.query) != '{}') {
        router.replace({ query: {} });
    }
    Object.keys(queryForm).map(key => {
        if (key != 'likes') {
            queryForm[key] = '';
        }
    });
    datas.value.forEach(pItem => {
        pItem.forEach(item => {
            if (item.noClear) {
                queryForm[item.key] = item.default;
            }
        });
    });
};

const setTime = val => {
    emit('filter', toRaw(queryForm));
};
const reset = () => {
    clear();
    // emit('filter', toRaw(queryForm))
};

//在onMounted中调用是为了pageRef可以加载好
onMounted(() => {
    props.onLoad && emit('filter', toRaw(queryForm));
});

defineExpose({
    reset,
});
</script>

<template>
    <div class="search-wrapper">
        <template v-if="datas">
            <el-row v-for="(pItem, pIndex) in datas" :key="pIndex" :gutter="gutter" class="search-item-line">
                <el-col v-for="(item, index) in pItem" :key="index" :span="item.width">
                    <!-- 日期区间 -->
                    <el-date-picker
                        v-if="item.type === Type.DATE_RANGE"
                        :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
                        :format="item.format || 'YYYY-MM-DD HH:mm:ss'"
                        style="width: 95%"
                        :value-format="item.format || 'YYYY-MM-DD HH:mm:ss'"
                        type="daterange"
                        unlink-panels
                        range-separator="至"
                        :disabled-date="item.disabledDate"
                        :start-placeholder="item.startPlaceholder || '开始日期'"
                        :end-placeholder="item.endPlaceholder || '结束日期'"
                        :shortcuts="regionDateShortcuts3"
                        v-model="queryForm[item.key || 'time']"
                        :clearable="!!!item.noClear"
                        @change="setTime"
                    ></el-date-picker>
                    <el-date-picker v-else-if="item.type === Type.DATE" :format="item.format || 'YYYY-MM-DD'" :value-format="item.format || 'YYYY-MM-DD'" type="date" unlink-panels :placeholder="item.placeholder || '开始时间'" style="width: 100%" v-model="queryForm[item.key]" :clearable="!!!item.noClear"></el-date-picker>
                    <!-- Select -data-placeholder-key-labelKey-valueKey -->
                    <el-select v-else-if="item.type === Type.SELECT && item.visible != false ? true : false" v-model="queryForm[item.key]" :placeholder="item.placeholder" filterable :clearable="!!!item.noClear" style="width: 100%" :style="item.style || {}">
                        <el-option v-for="(obj, index) in item.data" :key="obj[item.valueKey || 'value']" :label="obj[item.labelKey || 'label']" :value="obj[item.valueKey || 'value']"></el-option>
                    </el-select>
                    <el-select v-else-if="item.type === Type.REMOTE" v-model="queryForm[item.key]" :placeholder="item.placeholder" filterable remote :remote-method="item.remote" :clearable="!!!item.noClear" style="width: 100%" :style="item.style || {}">
                        <el-option v-for="(obj, index) in item.data" :key="obj[item.valueKey || 'value']" :label="obj[item.labelKey || 'label']" :value="obj[item.valueKey || 'value']"></el-option>
                    </el-select>
                    <!-- treeSelect -->
                    <el-tree-select v-else-if="item.type === Type.SELECT2" v-model="queryForm[item.key]" :placeholder="item.placeholder" :data="item.data" :check-strictly="!!item.strictly" :render-after-expand="false" filterable accordion :clearable="!!!item.noClear" style="width: 100%" :props="item.props" :node-key="item.nodeKey" />
                    <!-- cascader -->
                    <el-cascader v-else-if="item.type === Type.CASCADER" v-model="queryForm[item.key]" :placeholder="item.placeholder" :options="item.data" :props="item.props" filterable style="width: 100%" :clearable="!!!item.noClear" />
                    <!-- 输入框搜索 -->
                    <el-input style="width: 100% || 1px" v-else-if="item.type === Type.INPUT" :placeholder="item.placeholder" v-model.trim="queryForm[item.key]" clearable @keyup.enter="emit('filter', toRaw(queryForm))"></el-input>
                    <el-button v-else-if="item.type === Type.BUTTON" type="primary" @click="emit('filter', toRaw(queryForm))">
                        {{ item.text }}
                    </el-button>
                    <!-- 筛选按钮 -->
                    <template v-else-if="item.type === Type.SEARCH_BUTTON">
                        <el-button type="danger" @click="emit('filter', toRaw(queryForm))">查询</el-button>
                        <el-button type="danger" plain @click="reset">清空</el-button>
                    </template>
                    <!-- 导出按钮 -->
                    <template v-else-if="item.type === Type.EXPORT_BUTTON">
                        <el-button type="danger" @click="reset">查询</el-button>
                        <el-button type="danger" plain @click="emit('export', toRaw(queryForm))">导出</el-button>
                    </template>
                    <!-- 导出按钮 -->
                    <template v-else-if="item.type === Type.SEARCH_EXPORT_BUTTON">
                        <el-button type="danger" @click="emit('filter', toRaw(queryForm))">查询</el-button>
                        <!-- <el-button type="danger" :icon="!item.noIcon && Search" @click="emit('filter', toRaw(queryForm))">
                            查询
                        </el-button> -->
                        <el-button type="danger" plain @click="reset">清空</el-button>
                        <el-button type="danger" plain @click="emit('export', toRaw(queryForm))">导出</el-button>
                    </template>
                </el-col>
            </el-row>
        </template>
    </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
    .search-item-line {
        margin-bottom: 10px;
    }
}
</style>

<style lang="scss">
:root {
    --el-color-primary: #ff554b;
}
</style>
